import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/bill_provider.dart';
import '../../core/app_theme.dart';
// import '../../core/snackbar_helper.dart';
import 'add_edit_bill_screen.dart';
import '../../widgets/bill_group_list.dart';
// import 'bill_detail_screen.dart';


class BillListScreen extends StatefulWidget {
  const BillListScreen({super.key});

  @override
  State<BillListScreen> createState() => _BillListScreenState();
}

class _BillListScreenState extends State<BillListScreen> {
  String? _currentFilter;

  @override
  void initState() {
    super.initState();
    // 页面初始化时加载账单数据
    Future.microtask(() {
      Provider.of<BillProvider>(context, listen: false).loadBills();
    });
  }

  // 筛选账单方法
  void _filterBills(String? status) {
    setState(() {
      _currentFilter = status;
    });
    Provider.of<BillProvider>(context, listen: false)
        .loadBills(status: status);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('账单管理', style: AppTheme.titleLarge),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AddEditBillScreen(),
                ),
              ).then((result) {
                if (result == true) {
                  Provider.of<BillProvider>(context, listen: false)
                      .loadBills(status: _currentFilter);
                }
              });
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 筛选按钮
          _buildFilterButtons(),
          const SizedBox(height: 8),
          // 统计信息
          _buildStatistics(),
          const SizedBox(height: 8),
          // 分组列表
          Expanded(
            child: Consumer<BillProvider>(
              builder: (context, billProvider, child) {
                if (billProvider.isLoading) {
                  return const Center(child: CircularProgressIndicator());
                }
                
                if (billProvider.bills.isEmpty) {
                  return Center(
                    child: Padding(
                      padding: const EdgeInsets.all(24.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            _getEmptyStateIcon(),
                            size: 72,
                            color: Colors.grey[400],
                          ),
                          const SizedBox(height: 20),
                          Text(
                            _getEmptyStateMessage(),
                            style: const TextStyle(
                              fontSize: 20,
                              color: Colors.grey,
                              fontWeight: FontWeight.w500,
                            ),
                            textAlign: TextAlign.center,
                          ),
                          const SizedBox(height: 12),
                          Text(
                            _getEmptyStateHint(),
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[600],
                            ),
                            textAlign: TextAlign.center,
                          ),
                          const SizedBox(height: 24),
                          // 根据筛选状态提供不同的操作
                          if (_currentFilter != null)
                            Column(
                              children: [
                                ElevatedButton.icon(
                                  onPressed: () => _filterBills(null),
                                  icon: const Icon(Icons.list),
                                  label: const Text('查看全部账单'),
                                ),
                                const SizedBox(height: 12),
                                Text(
                                  '或',
                                  style: TextStyle(
                                    color: Colors.grey[500],
                                    fontSize: 12,
                                  ),
                                ),
                                const SizedBox(height: 12),
                                OutlinedButton.icon(
                                  onPressed: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => const AddEditBillScreen(),
                                      ),
                                    );
                                  },
                                  icon: const Icon(Icons.add),
                                  label: const Text('创建新账单'),
                                ),
                              ],
                            )
                          else
                            ElevatedButton.icon(
                              onPressed: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => const AddEditBillScreen(),
                                  ),
                                );
                              },
                              icon: const Icon(Icons.add),
                              label: const Text('创建第一个账单'),
                              style: ElevatedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                              ),
                            ),
                        ],
                      ),
                    ),
                  );
                }
                return const BillGroupList();
              },
            ),
          ),
        ],
      ),
    );
  }

  // 添加图标选择方法
  IconData _getEmptyStateIcon() {
    switch (_currentFilter) {
      case 'pending':
        return Icons.pending_actions;
      case 'completed':
        return Icons.check_circle_outline;
      case 'cancelled':
        return Icons.cancel_outlined;
      default:
        return Icons.receipt_long;
    }
  }

  String _getEmptyStateMessage() {
  switch (_currentFilter) {
    case 'pending':
      return '暂无待处理账单';
    case 'completed':
      return '暂无已完成账单';
    case 'cancelled':
      return '暂无已取消账单';
    default:
      return '暂无账单';
  }
}

  String _getEmptyStateHint() {
    switch (_currentFilter) {
      case 'pending':
        return '未完成状态的账单将显示在这里';
      case 'completed':
        return '已完成状态的账单将显示在这里';
      case 'cancelled':
        return '已取消状态的账单将显示在这里';
      default:
        return '点击下方按钮创建第一个账单';
    }
  }

  Widget _buildFilterButtons() {
    return Container(
      padding: const EdgeInsets.all(8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildFilterButton('全部', null, Colors.blue),
          _buildFilterButton('未完成', 'pending', Colors.orange),
          _buildFilterButton('已完成', 'completed', Colors.green),
          _buildFilterButton('已取消', 'cancelled', Colors.red),
        ],
      ),
    );
  }

  Widget _buildFilterButton(String text, String? status, Color color) {
    final isActive = _currentFilter == status;
    
    return Expanded(
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 4),
        child: ElevatedButton(
          onPressed: () => _filterBills(status),
          style: ElevatedButton.styleFrom(
            backgroundColor: isActive ? color : Colors.grey[300],
            foregroundColor: isActive ? Colors.white : Colors.grey[700],
            padding: const EdgeInsets.symmetric(vertical: 8),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: Text(
            text,
            style: const TextStyle(fontSize: 12),
          ),
        ),
      ),
    );
  }

  Widget _buildStatistics() {
    return Consumer<BillProvider>(
      builder: (context, billProvider, child) {
        if (billProvider.bills.isEmpty) {
          return const SizedBox();
        }

        final totalBills = billProvider.bills.length;
        final totalAmount = billProvider.bills.fold(
          0.0, 
          (sum, bill) => sum + bill.totalAmount
        );
        final pendingBills = billProvider.bills.where((b) => b.status == 'pending').length;

        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatItem('总账单', totalBills.toString(), Colors.blue),
              _buildStatItem('总金额', '¥${totalAmount.toStringAsFixed(2)}', Colors.green),
              _buildStatItem('待处理', pendingBills.toString(), Colors.orange),
            ],
          ),
        );
      },
    );
  }

  Widget _buildStatItem(String label, String value, Color color) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }
}